package gu.sql2java.excel;

import static com.google.common.base.Preconditions.checkNotNull;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import com.google.common.base.Throwables;

import gu.sql2java.BaseBean;

/**
 * {@link CustomBeanParser}接口实现,将Map转为{@link #beanClass}指定的BaseBean实例
 * @author guyadong
 *
 * @param <B>
 * @since 3.30.0
 */
public class BaseBeanParser<B extends BaseBean> implements CustomBeanParser{
	private final Class<B> beanClass;
	
	public BaseBeanParser(Class<B> beanClass) {
		this.beanClass = checkNotNull(beanClass,"beanClass is null") ;
	}
	@SuppressWarnings("unchecked")
	protected BaseBeanParser() {
    	Type superClass = getClass().getGenericSuperclass();
        this.beanClass = (Class<B>) getRawClass(((ParameterizedType) superClass).getActualTypeArguments()[0]);
	}
	private static Class<?> getRawClass(Type type){
        if(type instanceof Class<?>){
            return (Class<?>) type;
        } else if(type instanceof ParameterizedType){
            return getRawClass(((ParameterizedType) type).getRawType());
        } else{
            throw new IllegalArgumentException("invalid type");
        }
    }
	@Override
	public Object parse(Map<String, String> input) {
		try {
			return beanClass.newInstance().copyNoFilter(input);
		} catch (Exception e) {
			Throwables.throwIfUnchecked(e);
			throw new RuntimeException(e);
		}
	}
}